package databaseVersionControl.domain.dml;

import java.util.ArrayList;
import java.util.List;

import databaseVersionControl.infra.exception.DVCGeneralException;

public class Select extends DML {
	
	private List<String> columns = new ArrayList<String>();
	private String whereClause;
	
	public Select() {}
	
	public Select(String... columns) {
		if ( columns.length == 0 ) return; 
		initializeColumns(columns);
	}
	
	private void initializeColumns( String[] columns ) {
		for (int index = 0; index < columns.length; index++) 
			addColumn(columns[index]);
	}
	
	private void addColumn(String column) {
		this.columns.add(column.toUpperCase());
	}
	
	public Select from(String table) {
		this.table = table.toUpperCase();
		return this;
	}
	
	public Select where(String whereClause) {
		this.whereClause = whereClause.toUpperCase();
		return this;
	}
	
	private void validateStatement() {
		if (table == null) throw new DVCGeneralException("Cannot select without table.");
	}
	
	@Override
	public String sqlString() {
		validateStatement();
		
		StringBuilder builder = new StringBuilder("SELECT ");
		builder.append( columns.isEmpty() ? "* " : columnsToStatement() );
		builder.append("FROM " + table);
		
		if (whereClause != null) {
			builder.append(" WHERE ");
			builder.append(whereClause);
		}
		
		return builder.toString();
	}
	
	private String columnsToStatement() {
		StringBuilder builder = new StringBuilder(columns.get(0));
		columns.remove(0);
		
		for (String columnName : columns) {
			builder.append(", ");
			builder.append(columnName);
		}
		
		builder.append(" ");
		
		return builder.toString();
	}

}